package com.elektronikforumet.camalert;

import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.preference.PreferenceManager;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

/**
 * Extended from com.google.android.maps.Overlay.
 * It shows a speedcamera on the map.
 * 
 * @author Erik Abrahamsson
 */
public class MapCamOverlay extends Overlay {
	GeoPoint geoPoint;
    BitmapDrawable bmp;
    int mDirection;
	
    /**
     * MapCamOverlay constructor.
     * @param d An icon of type Drawable.
     * @param p GeoPoint where the icon should be placed.
     * @param dir Specifies the rotation of the camera.
     */
    public MapCamOverlay(Drawable d, GeoPoint p, int dir) {
        bmp = (BitmapDrawable) d;
        this.geoPoint = p;
        mDirection = dir;
    } 
    
    @Override
    public void draw(Canvas canvas, MapView mapView, boolean shadow) {
    	Projection projection = mapView.getProjection();

    	if (shadow == false) {
    		Point myPoint = new Point();
    		projection.toPixels(geoPoint, myPoint);
    		
    		int rad = 14;
    		Rect rect = new Rect(myPoint.x-rad, myPoint.y-rad, myPoint.x+rad, myPoint.y+rad);
        	
        	bmp.setBounds(rect);
        	bmp.setAlpha(170);
        	bmp.draw(canvas);
        	
        	Paint paint = new Paint();
        	paint.setColor(Color.RED);
        	paint.setAlpha(35);
        	paint.setAntiAlias(true);

        	//Draw arc which shows camera direction and warning distance
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mapView.getContext());
			int iDistAlert = Integer.parseInt(prefs.getString("distance_alert", "500"));
        	int arcSize = (int) projection.metersToEquatorPixels(iDistAlert * 2);
        	int arcAngle = 110;
        	
    		RectF rectF = new RectF(myPoint.x-arcSize, myPoint.y-arcSize, myPoint.x+arcSize, myPoint.y+arcSize);
        	canvas.drawArc(rectF, mDirection*90-arcAngle/2, arcAngle, true, paint);
    	}
    }
    
}
